package com.vietjetair.common;

import com.vietjetair.config.LogUtils;
import io.github.bonigarcia.wdm.ChromeDriverManager;
import io.github.bonigarcia.wdm.DriverManagerType;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.slf4j.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Administrator
 */
public class CommUtil {

    private static Logger logger = LogUtils.getCheckTicketLogger();
    private static Logger errorLogger = LogUtils.getCheckTicketErrorLogger();
    private static final String driverPath;
    private static final String linuxDriverPath;
    static {
        driverPath = CommUtil.class.getClassLoader().getResource("driver/chromedriver.exe").getPath();
        linuxDriverPath = CommUtil.class.getClassLoader().getResource("driver/chromedriver").getPath();
    }

    /**
     * 驱动浏览器初始化
     * @return
     */
    public static WebDriver initialization() {
        long time = System.currentTimeMillis();
        logger.info(OperationCodeEnum.BROWSERSTART.getText());
        DesiredCapabilities caps = null;
        try {
            caps = DesiredCapabilities.chrome();
            caps.setJavascriptEnabled(true);
            ChromeDriverManager.getInstance(DriverManagerType.CHROME).setup();
            System.setProperty("webdriver.chrome.driver", driverPath);
            ChromeOptions chromeOptions = new ChromeOptions();
            Map<String, Object> prefs = new HashMap<>(2);
            // 禁止加载js - 2就是代表禁止加载的意思
            prefs.put("profile.default_content_settings.javascript", 2);
            // 禁止加载css - 2就是代表禁止加载的意思
            prefs.put("profile.default_content_settings.images", 2);
            chromeOptions.setExperimentalOption("prefs", prefs);
            // 无头模式
            chromeOptions.addArguments("--headless");
            //请求头
            chromeOptions.addArguments("--user-agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'");
            // 沙箱
            chromeOptions.addArguments("--no-sandbox");
            // 隐身
            chromeOptions.addArguments("--incognito");
            // 语言
            chromeOptions.addArguments("--lang=zh_CN.UTF-8");
            // 使用一切手段加速
            chromeOptions.addArguments("--disable-plugins");
            // 禁用图像
            chromeOptions.addArguments("--disable-images");
            // 禁用gpu谷歌文档提到需要加上这个属性来规避bug
            chromeOptions.addArguments("--disable-gpu");
            // 禁用JavaScript
            chromeOptions.addArguments("--disable-javascript");
            //关闭"Chrome正在受到自动软件的控制"
            chromeOptions.addArguments("disable-infobars");
            chromeOptions.addArguments("disable-dev-shm-usage");
            //chromeOptions.addArguments("--proxy-server=socks5://47.244.23.34:24000");
            caps.setCapability(ChromeOptions.CAPABILITY,chromeOptions);
        /*ChromeDriver driver = new ChromeDriver(caps);
        driver.manage().window().maximize();*/
        } catch (Exception e) {
            e.printStackTrace();
            errorLogger.error(OperationCodeEnum.BROWSERERROR.getText(),e);
        } finally {
            logger.info(OperationCodeEnum.BROWSEREND.getText() +",耗时:"+(System.currentTimeMillis()-time)/1000.0);
        }
        return new ChromeDriver(caps);
    }


    public static void close(WebDriver driver,String msg){
        if (driver!=null) {
            driver.manage().deleteAllCookies();
            driver.close();
            logger.info(OperationCodeEnum.BROWSERCLOSE.getText()+msg);
        }
    }

    public static void quit(WebDriver driver,String msg){
        if (driver!=null){
            driver.manage().deleteAllCookies();
            driver.quit();
            logger.info(OperationCodeEnum.BROWSERQUIT.getText()+msg);
        }
    }


    public static void openTag(WebDriver driver,String baseUrl){
        JavascriptExecutor js = (JavascriptExecutor)driver;
        driver.navigate().to(baseUrl);
        js.executeScript("window.open()");
        ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
        driver.switchTo().window(tabs.get(1));
    }

    public static void closeTag(WebDriver driver){
        JavascriptExecutor js = (JavascriptExecutor)driver;
        js.executeScript("window.close();");
    }

    public static boolean ElementExist(WebDriver driver,By locator) {
        try {
            driver.findElement(locator);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public static void readRecords() {
        try {
            File file = new File("D:/te.txt");
            BufferedReader stringReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GB2312"));
            Stream<String> lines = stringReader.lines();
            List<String> collect = stringReader.lines().collect(Collectors.toList());
            collect.forEach(s -> System.out.println(s));
        }catch (Exception e){
            e.getMessage();
        }
    }
}
